plotly 入門

郭耀仁

2017-11-28

準備事項

安裝與載入

install.packages("plotly")
install.packages("gapminder")
install.pacakges("tidyverser")
library(plotly)
library(gapminder)
library(tidyverse)

gapminder 資料

還記得 Hans Rosling 的 The best stats you’ve ever seen 嗎?

dim(gapminder)
## [1] 1704    6
head(gapminder)
## # A tibble: 6 x 6
##       country continent  year lifeExp      pop gdpPercap
##        <fctr>    <fctr> <int>   <dbl>    <int>     <dbl>
## 1 Afghanistan      Asia  1952  28.801  8425333  779.4453
## 2 Afghanistan      Asia  1957  30.332  9240934  820.8530
## 3 Afghanistan      Asia  1962  31.997 10267083  853.1007
## 4 Afghanistan      Asia  1967  34.020 11537966  836.1971
## 5 Afghanistan      Asia  1972  36.088 13079460  739.9811
## 6 Afghanistan      Asia  1977  38.438 14880372  786.1134

繪製分配的圖形

直方圖

gapminder_2007 <- gapminder %>%
  filter(year == 2007)
p <- plot_ly(data = gapminder_2007, x = ~gdpPercap, type = "histogram")

顯示直方圖

p

盒鬚圖

p <- plot_ly(data = gapminder_2007, x = ~continent, y = ~lifeExp, color = ~continent, type = "box")

顯示盒鬚圖

p

繪製相關的圖形

散佈圖

p <- plot_ly(data = gapminder_2007, x = ~gdpPercap, y = ~lifeExp, color = ~continent, type = "scatter", mode = "markers")

顯示散佈圖

p

繪製排名的圖形

長條圖

north_asia <- gapminder_2007 %>%
  filter(country %in% c("China", "Taiwan", "Japan", "Korea, Rep."))
north_asia$country <- as.character(north_asia$country)
p <- plot_ly(data = north_asia, x = ~country, y = ~gdpPercap, type = "bar", color = ~country)

顯示長條圖

p

繪製時間序列的圖形

線圖

twn <- gapminder %>%
  filter(country == "Taiwan")
p <- plot_ly(data = twn, x = ~year, y = ~lifeExp, type = "scatter", mode = "lines")

顯示線圖

p

切割畫布

準備資料

north_asia <- gapminder %>%
  filter(country %in% c("China", "Taiwan", "Japan", "Korea, Rep."))
north_asia$country <- as.character(north_asia$country)
p1 <- north_asia %>%
  filter(country == "Japan") %>%
  plot_ly(x = ~year, y = ~gdpPercap,  type = "scatter", mode = "lines") %>%
  add_lines(name = ~"Japan")
p2 <- north_asia %>%
  filter(country == "Korea, Rep.") %>%
  plot_ly(x = ~year, y = ~gdpPercap,  type = "scatter", mode = "lines") %>%
  add_lines(name = ~"Korea, Rep.")

subplot 函數

subplot(p1, p2)